package com.zhz.mall.admin.modules.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.zhz.mall.admin.dto.OssPolicyResult;
import com.zhz.mall.admin.modules.oss.service.OssService;
import com.zhz.mall.admin.properties.OssConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @description: Oss处理实现类
 * @motto: 代码源于生活，高于生活艺术
 * @author: zhouhengzhe
 * @date: 2023/1/13 11:13
 * @since 1.0
 **/
@Slf4j
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private OssConfigProperties ossConfigProperties;

    /**
     * Oss上传签名生成
     *
     * @return
     */
    @Override
    public OssPolicyResult policy() {
        try {
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0L, ossConfigProperties.getMaxSize());
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossConfigProperties.getDir().getPath());
            String postPolicy = ossClient.generatePostPolicy(ossConfigProperties.getPolicy().getExpiration(), policyConditions);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            return OssPolicyResult
                    .builder()
                    .accessKeyId(ossClient.getCredentialsProvider().getCredentials().getAccessKeyId())
                    .policy(BinaryUtil.toBase64String(postPolicy.getBytes(StandardCharsets.UTF_8)))
                    .signature(postSignature)
                    .dir(ossConfigProperties.getDir().getPath())
                    .host(ossConfigProperties.getAction())
                    .build();
        } catch (Exception e) {
            log.error("签名生成失败", e);
            return new OssPolicyResult();
        }
    }
}
